<template>
  <div class="app-container">
    <el-row class="row">
      <div class="action">
        <el-button class="filter-item" icon="el-icon-plus" type="primary" @click="handleCreate">新增品牌</el-button>
      </div>
      <el-table :data="list"  element-loading-text="Loading" border fit highlight-current-row>
        <el-table-column align="center" label='时间' >
          <template slot-scope="scope">
            {{scope.row.createtime}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="品牌名称">
          <template slot-scope="scope">
            {{scope.row.bname}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{scope.row.delflagstr}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)" >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-row>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form autoComplete="on" :model="brandForm" :rules="brandRules" ref="brandForm"   label-position="left">
        <el-input type="hidden" v-model="brandForm.id"></el-input>
        <el-form-item label="品牌名称"  prop="bname">
          <el-input v-model="brandForm.bname" placeholder="请输入品牌名称,目前只支持phicomm和tenda"></el-input>
        </el-form-item>
        <el-form-item label="品牌描述"  prop="description">
          <el-input type="textarea" placeholder="请输入品牌描述" v-model="brandForm.description"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="delflag">
          <el-select v-model="brandForm.delflag" placeholder="请选择状态">
            <el-option v-for="item in  statusOptions" :key="item.key" :label="item.text" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">修改</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { validatAlphabets } from '@/utils/validate'
  import { fetchList, saveBrand } from '@/api/brand'
  import { parseTime } from '@/utils/index'
  export default {
    name: 'channel',
    data() {
      const validateBname = (rule, value, callback) => {
        if (!validatAlphabets(value)) {
          callback(new Error('只能填写英文字母'))
        } else {
          callback()
        }
      }
      return {
        list: [],
        total: null,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑品牌',
          create: '新建品牌'
        },
        statusOptions: [
          { key: 0, text: '启用' },
          { key: 1, text: '禁用' }
        ],
        brandRules: {
          bname: [{ required: true, message: '请输入品牌名称(只能填写英文字母)', trigger: 'blur', validator: validateBname },
            { min: 1, max: 20, message: '长度在1到20字符', trigger: 'blur' }],
          description: [{ min: 0, max: 100, message: '长度在0到100中文字', trigger: 'blur' }]
        },
        brandForm: {
          id: '',
          bname: '',
          description: '',
          delflag: '',
          delflagstr: ''
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      resetForm() {
        this.brandForm = {
          id: '',
          bname: '',
          description: '',
          delflag: undefined
        }
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['brandForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        this.brandForm = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['brandForm'].clearValidate()
        })
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          if (response.code === 1) {
            const list = response.data.list
            this.total = response.data.total
            this.list = []
            for (const v of list) {
              const item = {}
              item.id = v.id
              item.createtime = v.createtime
              item.bname = v.bname
              item.delflag = v.delflag
              item.description = v.description
              if (v.delflag === 0) {
                item.delflagstr = '启用'
              } else {
                item.delflagstr = '禁用'
              }
              this.list.push(item)
            }
            // Just to simulate the time of the request
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          } else if (response.code === -100) {
            this.$router.push({ path: '/login' })
          }
        })
      },
      createData() {
        this.$refs.brandForm.validate(valid => {
          if (valid) {
            saveBrand(this.brandForm).then(() => {
              const data = this.brandForm
              const time = parseTime(new Date())
              data.createtime = time
              if (this.brandForm.delflag === 0) {
                this.brandForm.delflagstr = '启用'
              } else {
                this.brandForm.delflagstr = '禁用'
              }
              this.list.unshift(data)
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('新建品牌失败！')
            return false
          }
        })
      },
      updateData() {
        this.$refs.brandForm.validate(valid => {
          if (valid) {
            saveBrand(this.brandForm).then(() => {
              for (const v of this.list) {
                if (v.id === this.brandForm.id) {
                  const index = this.list.indexOf(v)
                  if (this.brandForm.delflag === 0) {
                    this.brandForm.delflagstr = '启用'
                  } else {
                    this.brandForm.delflagstr = '禁用'
                  }
                  this.list.splice(index, 1, this.brandForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$message({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            console.log('更新品牌信息失败！')
            return false
          }
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .channel-container {
    padding: 32px;
    background-color: rgb(240, 242, 245);
    min-height: 800px;
    .chart-wrapper {
      background: #fff;
      padding: 16px 16px 0;
      margin-bottom: 32px;
    }
  }
  .row{
    background-color:#fff;
    padding:16px;
    margin-bottom:20px;
  }
  .action{
    margin-bottom:20px;
  }
  .el-dialg-w{
    width:30%;
  }
</style>
